<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
//use Illuminate\Support\Facades\Log;

use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTFactory;
class userC extends Controller
{
    protected $name = '用户管理';
    protected $find = ['a.id', 'a.userid', 'a.name', 'a.employeeid', 'a.tel', 'a.channelid', 'a.des', 'b.name as channel', 'a.providerid', 'a.customerid', 'a.state'];
    //登录
    public function login(Request $request)
    {
        try {
            $credentials = $request->only('name', 'password');
            // $email = $request->email;
            $name = trim($request->name);
            $password = trim($request->password);
            if (empty($name)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '姓名不能为空']);
            }
            if (empty($password)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '密码不能为空']);
            }
            $userx = User::where('name', $name)->first();
            if (empty($userx)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '用户不存在']);
            }
            if (Hash::check($password, $userx->password)) {
                //return $this->ajaxReturn(['code' => 0, 'msg' => '匹配']);
            } else {
                return $this->ajaxReturn(['code' => 0, 'msg' => '密码错误!', 'user' => Hash::make($password)]);
            }
            if (!$token = JWTAuth::attempt($credentials)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '用户凭证生成失败!']);
            }
            // 
            $FSQL = " select name as channelnm from channel where channelid='" . $userx->channelid . "' and isdel=0";
            $channelnm = DB::select($FSQL)[0]->channelnm;
            $userx->channelnm = $channelnm;
            // 解码 token
            $parsedToken = JWTAuth::setToken($token);
            $decoded = $parsedToken->getPayload();
            //记录登录日志
            $loglist = [];
            $loglist['Ip'] = $decoded['iss'];
            $loglist['token'] = $token;
            $loglist['Loginuserid'] = $userx->userid;
            $loglist['Loginuser'] = $userx->name;
            $loglist['Logintime'] = date('Y-m-d H:i:s');
            $loglist['timeoutcount'] = $decoded['exp'] - $decoded['nbf'];
            DB::table('logfile')->insert($loglist);
            return $this->ajaxReturn(['code' => 1, 'msg' => '登录成功!', 'token' => $token, 'data' => $userx, 'loglist' => $loglist]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => '登录失败!' ,'error'=>$e->getMessage()]);
        }
    }
    //注册
    public function register(Request $request)
    {
        try {
            $name = trim($request->name);
            $tel = trim($request->tel);
            $password = trim($request->password);
            $password_confirmation = trim($request->password_confirmation);
            if (empty($name)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '姓名不能为空']);
            }
            if (empty($tel)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '电话不能为空']);
            }
            if ($password !== $password_confirmation) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '确认密码不一致,请重新输入']);
            }
            $FSQL = " select userid from users where name='$name' and isdel=0";
            if (!empty(DB::select($FSQL))) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '当前姓名已经被注册']);
            }
            $FSQL = " select userid from users where tel='$tel' and isdel=0";
            if (!empty(DB::select($FSQL))) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '当前电话已经被注册']);
            }
            $FSQL = "select id from userapply where isdel=0 and tel='$tel' and name='$name' and applytype='用户注册' and state=0";
            if (!empty(DB::select($FSQL))) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '已经提交注册申请，请耐心等待审核']);
            }
            $usrlist = [
                'name' => $name,
                'tel' => $tel,
                'applytype' => '用户注册',
                'password' => Hash::make($password),
                'created_at' => date('Y-m-d H:i:s'),
            ];
            DB::table('userapply')->insert($usrlist);
            //获取最大编号
            // $FSQL = " SELECT MAX(CAST(CASE WHEN userid REGEXP '^[0-9]+$' THEN userid ELSE NULL END AS SIGNED)) AS userid FROM users;";
            // $userid = intval(DB::select($FSQL)[0]->userid);
            // if ($userid == 0) {
            //     $userid = '000001';
            // } else {
            //     $userid++;
            //     $userid = str_pad($userid, 6, '0', STR_PAD_LEFT);
            // }
            // // 创建用户
            // $user = User::create([
            //     'userid' => $userid,
            //     'name' => $name,
            //     'tel' => $tel,
            //     'password' => Hash::make($password),
            // ]);
            // 返回成功响应
            return $this->ajaxReturn(['code' => 1, 'msg' => '已提交申请！请联系管理员审核']);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => '登录失败!','error'=>$e->getMessage()]);
        }
    }
    //退出登录
    public function logout(Request $request)
    {
        try {
            $token = $request->bearerToken();
            JWTFactory::setRefreshFlow(true);
            JWTAuth::invalidate(JWTAuth::parseToken($token));
            //退出登录记录时间
            $EXESQL = "UPDATE logfile SET logouttime='" . date('Y-m-d H:i:s') . "' WHERE token ='$token'";
            DB::update($EXESQL);
            return $this->ajaxReturn(['code' => 1, 'msg' => '退出成功!']);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => '退出失败!','error'=>$e->getMessage()]);
        }
    }

    //获取用户列表
    public function getUserList(Request $request)
    {
        try {
            //$user = User::all();
            $param = json_decode($request->param, true);
            $userid = $this->I($param['userid'] ?? null);
            $name = $this->I($param['name'] ?? null);
            $tel = $this->I($param['tel'] ?? null);
            $channelid = $this->I($param['channelid'] ?? null);
            $isuse = intval($this->I($param['isuse'] ?? null));
            $rolenm = $this->I($param['rolenm'] ?? null);
            $employeeid = $this->I($param['employeeid'] ?? null);
            $page = intval($this->I($param['page'] ?? 1));
            $pagecount = intval($this->I($param['pagecount'] ?? 10));
            $where = ' a.isdel=0';
            if (!empty($name)) {
                $where .= ' and a.name like "%' . $name . '%"';
            }
            if (!empty($userid)) {
                $where .= " and a.userid = '$userid'";
            }
            if (!empty($tel)) {
                $where .= " and a.tel = '$tel'";
            }
            if (!empty($isuse)) {
                $where .= " and a.isuse = '$isuse'";
            }
            if (!empty($channelid)) {
                $where .= " and a.channelid = '$channelid'";
            }
            if (!empty($employeeid)) {
                $where .= " and a.employeeid = '$employeeid'";
            }
            if (!empty($rolenm)) {
                $where .= " and exists(
                    select 1 from userrole as c 
                    inner join UsrGroup as d on c.roleid=d.id
                    where c.userid=a.id and c.isdel=0 and d.isdel=0 and d.name='$rolenm'
                ) ";
            }
            $temp = DB::table('users as a')
                ->leftjoin(
                    'channel as b',
                    function ($join) {
                        $join->on('a.channelid', '=', 'b.channelid')
                            ->where('b.isdel', '=', 0);
                    }
                ) // 多表连接
                ->select($this->find) // 确保没有多余的空格
                ->whereRaw($where)
                ->paginate($pagecount, ['id'], 'page', $page)// 控制页码，默认每页 10 条
                ->toArray();
            $res = $temp['data'];
            $allcount = $temp['total'];
            foreach ($res as $k) {
                $userid = $k->id;
                $k->employeenm = DB::table('employee')->where('employeeid', $k->employeeid)->value('name');
                $k->role = DB::table('userrole')
                    ->join('UsrGroup', 'userrole.roleid', '=', 'UsrGroup.id')
                    ->select(['userrole.id', 'UsrGroup.id as roleid0', 'userrole.userid', 'UsrGroup.des', 'UsrGroup.usrgroupid as roleid', 'UsrGroup.name as rolenm', 'userrole.isdel'])
                    ->whereRaw(" userrole.userid=$userid and userrole.isdel=0 and UsrGroup.isdel=0")->get();
                $role = [];
                if (!empty($k->role)) {
                    foreach ($k->role as $key) {
                        $role[] = $key->rolenm;
                    }
                }
                $k->rolenms = implode("/", $role);
            }
            // 构建查询
            // $query = DB::table('users as a')
            // ->leftjoin('channel as b', 
            // function($join) {
            //     $join->on('a.channelid', '=', 'b.channelid')
            //          ->where('b.isdel', '=', 0); 
            // }) // 多表连接
            // ->select($this->find) // 确保没有多余的空格
            // ->whereRaw($where);
            // $fullSql = $this->getsql($query);
            return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '|查询成功!', 'count' => $allcount, 'data' => $res]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => $this->name . '|查询失败!','error'=>$e->getMessage()]);
        }
    }

    //修改用户信息
    public function changeUserInfo(Request $request)
    {
        try {
            $usr = $this->decodetoken();
            $param = json_decode($request->param, true);
            $id = $this->I($param['id'] ?? null);
            //$userid = $this->I($param['userid'] ?? null);
            $name = $this->I($param['name'] ?? null);
            $channelid = $this->I($param['channelid'] ?? null);
            $state = intval($this->I($param['state'] ?? null));
            $tel = $this->I($param['tel'] ?? null);
            $employeeid = $this->I($param['employeeid'] ?? null);
            $des = $this->I($param['des'] ?? null);
            $role = $this->I($param['role'] ?? null);
            if (empty($id)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '用户id不能为空']);
            }
            if (empty($name)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '用户姓名不能为空']);
            }
            if (!empty($tel)) {
                $FSQL = " select userid from users where tel='$tel' and id<>$id";
                if (!empty(DB::select($FSQL))) {
                    return $this->ajaxReturn(['code' => 0, 'msg' => '当前电话已经被注册,你不能修改']);
                }
            }
            $userinfo = User::find($id);
            if ($userinfo->name == 'admin') {
                return $this->ajaxReturn(['code' => 0, 'msg' => '系统管理员账号不能做任何修改']);
            }
            if (!empty($role)) {
                foreach ($role as $key) {
                    $rolelist = [];
                    $recordid = $key['id'];
                    $rolelist['userid'] = $id;
                    $rolelist['roleid'] = $key['roleid0'];
                    $rolelist['isdel'] = $key['isdel'];
                    if (!empty($recordid)) {
                        DB::table('userrole')->where('id', $recordid)->update($rolelist);
                    } else {
                        DB::table('userrole')->insert($rolelist);
                    }
                }
            }
            $usrlist = [];
            $usrlist['name'] = $name;
            $usrlist['state'] = $state;
            $usrlist['tel'] = $tel;
            $usrlist['channelid'] = $channelid;
            $usrlist['employeeid'] = $employeeid;
            $usrlist['des'] = $des;
            $usrlist['modifier'] = $usr->name;
            $userinfo->update($usrlist);
            //记录日志
            $this->log(['type' => '修改', 'billcaption' => '用户管理', 'des' => '操作人[修改]了用户|[' . $name . '],|数据为|[' . json_encode($usrlist) . ']']);
            return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '|修改成功!', 'data' => $usr]);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => '修改失败!','error'=>$e->getMessage()]);
        }
    }

    //删除用户信息
    public function delete(Request $request)
    {
        try {
            $param = json_decode($request->param, true);
            $id = $this->I($param['id'] ?? null);
            if (empty($id)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '删除失败!用户ID为空']);
            }
            $uptab = User::find($id);
            if (empty($uptab)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '删除失败!用户不存在']);
            }
            $uptab->isdel = 1;
            $res = $uptab->save();
            if (empty($res)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '删除失败!']);
            }
            //记录日志
            $this->log(['type' => '删除', 'billcaption' => '用户管理', 'des' => '操作人[删除]了用户|[' . $uptab->name . '],|ID为|[' . $uptab->userid . ']']);
            return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '|删除成功!']);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => '修改失败!','error'=>$e->getMessage()]);
        }
    }

    //修改归属组织
    public function Setchannel(Request $request)
    {
        try {
            $param = json_decode($request->param, true);
            $id = $this->I($param['id'] ?? null);
            $channelid = $this->I($param['channelid'] ?? null);
            if (empty($id)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '修改失败!用户ID为空']);
            }
            $uptab = User::find($id);
            if (empty($uptab)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '修改失败!用户不存在']);
            }
            $uptab->channelid = $channelid;
            $res = $uptab->save();
            if (empty($res)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '修改失败!']);
            }
            //记录日志
            $this->log(['type' => '修改', 'billcaption' => '用户管理', 'des' => '操作人[修改]了用户组织|[' . $uptab->name . '],|组织编号为|[' . $channelid . ']']);
            return $this->ajaxReturn(['code' => 1, 'msg' => '组织切换成功!']);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => '修改失败!','error'=>$e->getMessage()]);
        }
    }

    //修改密码
    public function changePassword(Request $request)
    {
        try {
            $usr = $this->decodetoken();
            $param = json_decode($request->param, true);
            $id = $this->I($param['id'] ?? null);
            $oldpassword = $this->I($param['oldpassword'] ?? null);
            $password = $this->I($param['password'] ?? null);
            $password_confirmation = $this->I($param['password_confirmation'] ?? null);
            if ($password !== $password_confirmation) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '确认密码不一致,请重新输入']);
            }
            $password_confirmation = trim($request->password_confirmation);

            $userx = User::where('id', $id)->first();
            if (empty($userx)) {
                return $this->ajaxReturn(['code' => 0, 'msg' => '用户不存在']);
            }
            if ($userx->name == 'admin') {
                return $this->ajaxReturn(['code' => 0, 'msg' => '系统管理员账号不能做任何修改']);
            }
            //如果是本人修改自己的密码，则无须校验
            if ($usr->id !== $id) {
                //通过操作人ID判断是否系统管理员
                $operatorid = $usr->id;
                $temp = DB::table('userrole')
                    ->join('UsrGroup', 'userrole.roleid', '=', 'UsrGroup.id')
                    ->select(['userrole.id', 'UsrGroup.id as roleid0', 'userrole.userid', 'UsrGroup.des', 'UsrGroup.usrgroupid as roleid', 'UsrGroup.name as rolenm', 'userrole.isdel'])
                    ->whereRaw(" userrole.userid=$operatorid and userrole.isdel=0 and UsrGroup.isdel=0 and UsrGroup.name='系统管理员'")->get();
                //系统管理员可直接修改密码,否则校验密码是否与原密码一致
                if (empty($temp)) {
                    if (!Hash::check($oldpassword, $userx->password)) {
                        return $this->ajaxReturn(['code' => 0, 'msg' => '修改失败,原密码错误!', 'user' => Hash::make($password)]);
                    }
                }
            } 
            //修改密码
            $userx->update(['password' => Hash::make($password)]);
            //记录日志
            $this->log(['type' => '修改', 'billcaption' => '用户管理', 'des' => '操作人[修改]了用户密码|[' . $userx->name . '],|修改密码为|[' . $password . ']']);
            return $this->ajaxReturn(['code' => 1, 'msg' => $this->name . '修改成功!']);
        } catch (\Exception $e) {
            return $this->ajaxReturn(['code' => 0, 'msg' => '修改失败!' ,'error'=>$e->getMessage()]);
        }
    }
}